package com.example.day0820_data;

import com.example.day0820_data.slice.MainAbilitySlice;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.window.dialog.ToastDialog;
import ohos.bundle.IBundleManager;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.Resource;
import ohos.security.SystemPermission;

import java.io.File;
import java.io.FileOutputStream;

public class MainAbility extends Ability {
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setMainRoute(MainAbilitySlice.class.getName());
        requestPermission();
    }

    //申请权限
    private void requestPermission() {
        String[] permissions = new String[]{SystemPermission.WRITE_USER_STORAGE};
        if (verifySelfPermission(SystemPermission.WRITE_USER_STORAGE) != IBundleManager.PERMISSION_GRANTED) {
            requestPermissionsFromUser(permissions, 0);
        }
    }

    //权限回调
    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
        if (permissions == null || permissions.length == 0 || grantResults == null || grantResults.length == 0) {
            super.onRequestPermissionsFromUserResult(requestCode, permissions, grantResults);
            return;
        }
        if (requestCode == 0) {
            if (grantResults[0] == IBundleManager.PERMISSION_DENIED) {
                terminateAbility();
            }
        }
        if (requestCode == 0) {
            if (grantResults[0] == IBundleManager.PERMISSION_GRANTED) {
                new ToastDialog(this).setText("已授权").show();
                //创建文件
                writeToDisk();
            }
        }
    }
    private void writeToDisk(){
        String rawFilePath = "entry/resources/rawfile/Test_Text.txt";
        //获取内部存储路径 /data/user/0/com.xxxx/files
        String internalFilePath = getFilesDir()+"/Test_Text.txt";
        File file = new File(internalFilePath);
        if(file.exists()){
            return;
        }
        RawFileEntry rawFileEntry = getResourceManager().getRawFileEntry(rawFilePath);
        try {
            FileOutputStream outputStream = new FileOutputStream(new File(internalFilePath));
            Resource resource = rawFileEntry.openRawFile();
            byte[] cache = new byte[1024];
            int len = resource.read(cache);
            while (len!=-1){
                outputStream.write(cache,0,len);
                len = resource.read(cache);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
